﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
#if !PHONE
using System.Text.RegularExpressions;
#endif

namespace Microsoft.Popfly.GameCreator.GameEngine
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            this.Startup += this.Application_Startup;
#if PHONE
            UnhandledException += new EventHandler<ApplicationUnhandledExceptionEventArgs>(Application_UnhandledException);
#else
            this.UnhandledException += this.Application_UnhandledException;
#endif
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            bool mute = e.InitParams.ContainsKey("mute") && e.InitParams["mute"] == "true";
            this.RootVisual = new PlaySurface(
                    mute
                );
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
#if PHONE
                // An unhandled exception has occurred, break in the debugger
                System.Diagnostics.Debugger.Break();
#else

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;

                try
                {
                    string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                    errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                    System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");");
                }
                catch (Exception)
                {
                }
#endif
            }
#if PHONE
            else
            {
                // By default show the error
                e.Handled = true;
                MessageBox.Show(e.ExceptionObject.Message + Environment.NewLine + e.ExceptionObject.StackTrace,
                    "Error", MessageBoxButton.OK);
            }
#endif
        }
    }
}